import {
  Form, Input, Button, Select, message,
} from 'antd';
import React from 'react';
import { register } from 'services/user';

const { Option } = Select;
const idPattern = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/;

class RegistrationForm extends React.Component {
  constructor() {
    super();

    this.state = {
      confirmDirty: false,
    };
  }

  handleSubmit = async (e) => {
    e.preventDefault();
    const { form } = this.props;

    try {
      await form.validateFieldsAndScroll();
      const registerData = {
        userId: form.getFieldValue('userId'),
        username: form.getFieldValue('userName'),
        password: form.getFieldValue('password'),
        phone: form.getFieldValue('phone'),
        role: parseInt(form.getFieldValue('role'), 0),
      };

      await register(registerData);
      message.success('注册成功');
    } catch (err) {
      console.error(err);
    }
  };

  handleConfirmBlur = (e) => {
    const { value } = e.target;
    const { confirmDirty } = this.state;
    this.setState({ confirmDirty: confirmDirty || !!value });
  };

  compareToFirstPassword = (rule, value, callback) => {
    const { form } = this.props;
    if (value && value !== form.getFieldValue('password')) {
      callback('两次密码不一致!');
    } else {
      callback();
    }
  };

  validateToNextPassword = (rule, value, callback) => {
    const { confirmDirty } = this.state;
    const { form } = this.props;
    if (value && confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    callback();
  };

  validateId = (rule, value, callback) => {
    if (value && !idPattern.test(value)) {
      callback('工号名称不合规! (应只包含小写字母数字与连接符"-", 且以字母开头, 以字母或数字结束)');
    }
    callback();
  }

  render() {
    const { form } = this.props;
    const { getFieldDecorator } = form;

    return (
      <Form
        labelCol={{ xs: { span: 24 }, sm: { span: 6 } }}
        wrapperCol={{
          xs: { span: 24 },
          sm: { span: 18 },
        }}
        onSubmit={this.handleSubmit}
      >
        <Form.Item label="工号">
          {getFieldDecorator('userId', {
            rules: [
              {
                required: true,
                message: '请输入工号!',
              },
              {
                validator: this.validateId,
              },
            ],
          })(<Input />)}
        </Form.Item>
        <Form.Item label="用户名">
          {getFieldDecorator('userName', {
            rules: [
              {
                required: true,
                message: '请输入用户名!',
              },
            ],
          })(<Input />)}
        </Form.Item>

        <Form.Item label="密码" hasFeedback>
          {getFieldDecorator('password', {
            rules: [
              {
                required: true,
                message: '请输入密码!',
              },
              {
                validator: this.validateToNextPassword,
              },
            ],
          })(<Input.Password />)}
        </Form.Item>
        <Form.Item label="确认密码" hasFeedback>
          {getFieldDecorator('confirm', {
            rules: [
              {
                required: true,
                message: '请确认密码!',
              },
              {
                validator: this.compareToFirstPassword,
              },
            ],
          })(<Input.Password onBlur={this.handleConfirmBlur} />)}
        </Form.Item>

        <Form.Item label="手机号">
          {getFieldDecorator('phone', {
            rules: [{ required: true, message: '请输入手机号!' }],
          })(<Input addonBefore="+86" style={{ width: '100%' }} />)}
        </Form.Item>

        <Form.Item label="角色">
          {getFieldDecorator('role', {
            rules: [{ required: true, message: '请选择角色!' }],
          })(
            <Select style={{ width: '32%' }}>
              <Option value="0">运维人员</Option>
              <Option value="1">管理人员</Option>
              <Option value="2">工艺人员</Option>
              <Option value="3">操作人员</Option>
            </Select>,
          )}
        </Form.Item>

        <Form.Item
          wrapperCol={{
            xs: { span: 24, offset: 0 },
            sm: { span: 24, offset: 6 },
          }}
        >
          <Button type="primary" htmlType="submit">
            注册
          </Button>
        </Form.Item>
      </Form>
    );
  }
}

const WrappedRegistrationForm = Form.create({})(RegistrationForm);

export default WrappedRegistrationForm;
